package com.crazy.base.common.utils.servicelocate;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringServiceRegistry implements ServiceRegistry, ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ServiceLocator.setRegistry(this);
        this.applicationContext = applicationContext;
    }

    @Override
    public <T> T getService(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    @Override
    public <T> T getService(String beanName, Class<T> clazz) {
        return applicationContext.getBean(beanName, clazz);
    }

    @Override
    public <T> void register(Class<T> clazz) {
        DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory)this.applicationContext.getAutowireCapableBeanFactory();
        BeanDefinition beanDefinition = new GenericBeanDefinition();
        beanDefinition.setBeanClassName(clazz.getName());
        beanFactory.registerBeanDefinition(clazz.getName(), beanDefinition);
    }
}
